/**
 * 评价模块工具函数
 */

import {
  EVAL_PLAN_STATUS_TEXT,
  EVAL_PLAN_STATUS_TAG_TYPE,
  AUDIT_STATUS_TEXT,
  AUDIT_STATUS_TAG_TYPE,
  REGISTRATION_STATUS_TEXT,
  REGISTRATION_STATUS_TAG_TYPE,
  SCORE_STATUS_TEXT,
  SCORE_STATUS_TAG_TYPE,
  HANDLE_STATUS_TEXT,
  HANDLE_STATUS_TAG_TYPE,
  MONITOR_STATUS_TEXT,
  MONITOR_STATUS_TAG_TYPE,
  TEMPLATE_STATUS_TEXT,
  TEMPLATE_STATUS_TAG_TYPE,
  COMMON_STATUS_TEXT,
  COMMON_STATUS_TAG_TYPE
} from '@/utils/constants/eval'

/**
 * 获取评价计划状态文本
 */
export function getPlanStatusText(status: number): string {
  return EVAL_PLAN_STATUS_TEXT[status] || '未知'
}

/**
 * 获取评价计划状态标签类型
 */
export function getPlanStatusTagType(status: number): string {
  return EVAL_PLAN_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取审核状态文本
 */
export function getAuditStatusText(status: number): string {
  return AUDIT_STATUS_TEXT[status] || '未知'
}

/**
 * 获取审核状态标签类型
 */
export function getAuditStatusTagType(status: number): string {
  return AUDIT_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取注册状态文本
 */
export function getRegistrationStatusText(status: number): string {
  return REGISTRATION_STATUS_TEXT[status] || '未知'
}

/**
 * 获取注册状态标签类型
 */
export function getRegistrationStatusTagType(status: number): string {
  return REGISTRATION_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取评分状态文本
 */
export function getScoreStatusText(status: number): string {
  return SCORE_STATUS_TEXT[status] || '未知'
}

/**
 * 获取评分状态标签类型
 */
export function getScoreStatusTagType(status: number): string {
  return SCORE_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取处理状态文本
 */
export function getHandleStatusText(status: number): string {
  return HANDLE_STATUS_TEXT[status] || '未知'
}

/**
 * 获取处理状态标签类型
 */
export function getHandleStatusTagType(status: number): string {
  return HANDLE_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取监控状态文本
 */
export function getMonitorStatusText(status: number): string {
  return MONITOR_STATUS_TEXT[status] || '未知'
}

/**
 * 获取监控状态标签类型
 */
export function getMonitorStatusTagType(status: number): string {
  return MONITOR_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取模板状态文本
 */
export function getTemplateStatusText(status: number): string {
  return TEMPLATE_STATUS_TEXT[status] || '未知'
}

/**
 * 获取模板状态标签类型
 */
export function getTemplateStatusTagType(status: number): string {
  return TEMPLATE_STATUS_TAG_TYPE[status] || ''
}

/**
 * 获取通用状态文本
 */
export function getCommonStatusText(status: number): string {
  return COMMON_STATUS_TEXT[status] || '未知'
}

/**
 * 获取通用状态标签类型
 */
export function getCommonStatusTagType(status: number): string {
  return COMMON_STATUS_TAG_TYPE[status] || ''
}

/**
 * 根据分数和满分计算得分率标签类型
 */
export function getScoreTagType(score: number, maxScore: number): string {
  if (!maxScore || maxScore === 0) return ''
  
  const rate = score / maxScore
  if (rate >= 0.9) return 'success'
  if (rate >= 0.8) return 'primary'
  if (rate >= 0.6) return 'warning'
  return 'danger'
}

/**
 * 根据等级评定获取标签类型
 */
export function getGradeLevelTagType(gradeLevel: string): string {
  const typeMap = {
    '优秀': 'success',
    '良好': 'primary',
    '合格': 'warning',
    '不合格': 'danger'
  }
  return typeMap[gradeLevel] || ''
}

/**
 * 验证身份证号格式
 */
export function validateIdNumber(idNumber: string): boolean {
  if (!idNumber) return false
  return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idNumber)
}

/**
 * 验证手机号格式
 */
export function validateMobile(mobile: string): boolean {
  if (!mobile) return false
  return /^1[3-9]\d{9}$/.test(mobile)
}

/**
 * 验证邮箱格式
 */
export function validateEmail(email: string): boolean {
  if (!email) return false
  return /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 生成随机字符串
 */
export function generateRandomString(length: number = 8): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 计算年龄
 */
export function calculateAge(birthDate: string | Date): number {
  const birth = new Date(birthDate)
  const today = new Date()
  let age = today.getFullYear() - birth.getFullYear()
  const monthDiff = today.getMonth() - birth.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  
  return age
}

/**
 * 计算工作年限
 */
export function calculateWorkYears(startDate: string | Date): number {
  const start = new Date(startDate)
  const today = new Date()
  const diffTime = Math.abs(today.getTime() - start.getTime())
  const diffYears = Math.floor(diffTime / (1000 * 60 * 60 * 24 * 365.25))
  
  return diffYears
}

/**
 * 检查日期范围是否有效
 */
export function isValidDateRange(startDate: string | Date, endDate: string | Date): boolean {
  const start = new Date(startDate)
  const end = new Date(endDate)
  return start <= end
}

/**
 * 检查时间是否在范围内
 */
export function isTimeInRange(checkTime: string | Date, startTime: string | Date, endTime: string | Date): boolean {
  const check = new Date(checkTime)
  const start = new Date(startTime)
  const end = new Date(endTime)
  return check >= start && check <= end
}

/**
 * 深拷贝对象
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as unknown as T
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as unknown as T
  }
  
  if (typeof obj === 'object') {
    const clonedObj = {} as T
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
  
  return obj
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number,
  immediate?: boolean
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout | null = null
  
  return function executedFunction(...args: Parameters<T>) {
    const later = () => {
      timeout = null
      if (!immediate) func(...args)
    }
    
    const callNow = immediate && !timeout
    
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    
    if (callNow) func(...args)
  }
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean
  
  return function executedFunction(...args: Parameters<T>) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}
